package com.javaProject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaProject.entity.Userkey;
import com.javaProject.service.UserkeyService;
import com.javaProject.mapper.UserkeyMapper;
import org.springframework.stereotype.Service;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
* @author ASUS
* @description 针对表【userkey】的数据库操作Service实现
* @createDate 2024-05-04 17:11:14
*/
@Service
public class UserkeyServiceImpl extends ServiceImpl<UserkeyMapper, Userkey>
    implements UserkeyService{

    @Override
    public PrivateKey getPrivateKey(String username) throws NoSuchAlgorithmException, InvalidKeySpecException {
        QueryWrapper<Userkey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Userkey key = this.getOne(queryWrapper);
        if (key == null) {
            return null;
        }
        byte[] keyBytes = key.getPkey();
        KeyFactory keyFactory = KeyFactory.getInstance("EC"); // 根据您的加密算法选择合适的算法，比如"RSA", "DSA", "EC"
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    @Override
    public boolean saveKey(String username, PrivateKey privateKey) {
        Userkey key = new Userkey();
        key.setUsername(username);
        byte[] privateKeyBytes = privateKey.getEncoded();
        key.setPkey(privateKeyBytes);
        if (this.count(new QueryWrapper<Userkey>().eq("username", username)) > 0) {
            return this.update(key, new QueryWrapper<Userkey>().eq("username", username));
        }
        return this.save(key);
    }
}




